//
//  WJPDFTabBarView.swift
//  PDFSign
//
//  Created by 李永彬 on 2025/9/23.
//

import UIKit
import SnapKit

class WJPDFTabBarView: UIView {
    
    // MARK: - UI Components
    private let containerStackView = UIStackView()
    private var buttons: [UIButton] = []
    private var titleLabels: [UILabel] = []
    private var buttonContainers: [UIView] = [] // 保存容器引用
    
    // MARK: - Properties
    var buttonTappedHandler: ((Int) -> Void)?
    
    // 按钮配置数据
    private let buttonConfigs: [(title: String, imageName: String)] = [
        ("Signature", "Icon_line_sign"),
        ("Draw", "Icon_line_draw"),
        ("Font", "Icon_fill_font")
    ]
    
    // MARK: - Initialization
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
        setupConstraints()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - Setup Methods
    private func setupUI() {
        backgroundColor = UIColor(hex: "#FFFFFF")
        
        // 设置容器StackView
        containerStackView.axis = .horizontal
        containerStackView.distribution = .fillEqually
        containerStackView.alignment = .center
        containerStackView.spacing = 0
        addSubview(containerStackView)
        
        // 创建按钮和标题
        createButtons()
    }
    
    private func createButtons() {
        for (index, config) in buttonConfigs.enumerated() {
            // 创建按钮容器
            let buttonContainer = UIView()
            buttonContainer.backgroundColor = .clear
            buttonContainer.tag = index
            buttonContainer.isUserInteractionEnabled = true
            
            // 为容器添加点击手势
            let tapGesture = UITapGestureRecognizer(target: self, action: #selector(containerTapped(_:)))
            buttonContainer.addGestureRecognizer(tapGesture)
            
            // 创建按钮
            let button = UIButton(type: .custom)
            button.tag = index
            button.setImage(UIImage(named: config.imageName), for: .normal)
            button.imageView?.contentMode = .scaleAspectFit
            button.isUserInteractionEnabled = false // 禁用按钮自身的交互，让容器处理
            buttonContainer.addSubview(button)
            buttons.append(button)
            
            // 创建标题标签
            let titleLabel = UILabel()
            titleLabel.text = config.title
            titleLabel.font = UIFont.montserratRegular(12)
            titleLabel.textColor = UIColor(hex: "#121212")
            titleLabel.textAlignment = .center
            titleLabel.numberOfLines = 1
            titleLabel.isUserInteractionEnabled = false
            buttonContainer.addSubview(titleLabel)
            titleLabels.append(titleLabel)
            
            // 保存容器引用
            buttonContainers.append(buttonContainer)
            
            // 添加按钮容器到StackView
            containerStackView.addArrangedSubview(buttonContainer)
        }
    }
    
    private func setupConstraints() {
        containerStackView.snp.makeConstraints { make in
            make.leading.trailing.equalToSuperview()
            make.top.equalToSuperview().offset(5)
            make.height.equalTo(49)
        }
        
        // 为每个按钮容器设置内部约束
        for (index, buttonContainer) in containerStackView.arrangedSubviews.enumerated() {
            let button = buttons[index]
            let titleLabel = titleLabels[index]
            
            button.snp.makeConstraints { make in
                make.top.equalToSuperview()
                make.centerX.equalToSuperview()
                make.width.height.equalTo(24)
            }
            
            titleLabel.snp.makeConstraints { make in
                make.top.equalTo(button.snp.bottom).offset(4)
                make.centerX.equalToSuperview()
                make.leading.greaterThanOrEqualToSuperview().offset(4)
                make.trailing.lessThanOrEqualToSuperview().offset(-4)
            }
            
            // 确保容器可以响应点击
            buttonContainer.snp.makeConstraints { make in
                make.height.equalTo(49)
            }
        }
    }
    
    // MARK: - Public Methods
    /// 更新按钮状态
    func updateButtonState(at index: Int, isSelected: Bool) {
        guard index >= 0 && index < buttons.count else { return }
        
        let button = buttons[index]
        let titleLabel = titleLabels[index]
        
        if isSelected {
            button.tintColor = UIColor(hex: "#007AFF")
            titleLabel.textColor = UIColor(hex: "#007AFF")
            // 可选：为选中状态添加背景色
            buttonContainers[index].backgroundColor = UIColor(hex: "#007AFF").withAlphaComponent(0.1)
        } else {
            button.tintColor = UIColor(hex: "#121212")
            titleLabel.textColor = UIColor(hex: "#121212")
            buttonContainers[index].backgroundColor = .clear
        }
    }
    
    /// 设置按钮图片
    func setButtonImage(at index: Int, image: UIImage?, for state: UIControl.State = .normal) {
        guard index >= 0 && index < buttons.count else { return }
        buttons[index].setImage(image, for: state)
    }
    
    /// 设置按钮标题
    func setButtonTitle(at index: Int, title: String) {
        guard index >= 0 && index < titleLabels.count else { return }
        titleLabels[index].text = title
    }
    
    /// 启用/禁用按钮
    func setButtonEnabled(at index: Int, enabled: Bool) {
        guard index >= 0 && index < buttons.count else { return }
        buttons[index].isEnabled = enabled
        titleLabels[index].alpha = enabled ? 1.0 : 0.5
        buttonContainers[index].alpha = enabled ? 1.0 : 0.5
        buttonContainers[index].isUserInteractionEnabled = enabled
    }
    
    // MARK: - Actions
    @objc private func containerTapped(_ gesture: UITapGestureRecognizer) {
        guard let container = gesture.view else { return }
        let index = container.tag
        
        // 为整个容器添加点击动画
        UIView.animate(withDuration: 0.1, animations: {
            container.transform = CGAffineTransform(scaleX: 0.95, y: 0.95)
            container.alpha = 0.8
        }) { _ in
            UIView.animate(withDuration: 0.1) {
                container.transform = CGAffineTransform.identity
                container.alpha = 1.0
            }
        }
        
        buttonTappedHandler?(index)
    }
    
    // 保留原有的按钮点击方法（虽然现在可能不会被调用）
    @objc private func buttonTapped(_ sender: UIButton) {
        let index = sender.tag
        buttonTappedHandler?(index)
    }
}
